package com.example.thread.day12ReentrantLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock获取锁的过程是可中断的
 * 对于synchronized关键字，如果一个线程在等待获取锁，最终只有两个结果
 *  1.要么获取到锁然后继续后面的操作
 *  2.要么一直等待，直到其他线程释放锁为止。
 *
 * 对于ReentrantLock
 *  1.ReentrantLock中必须使用实例方法lockInterruptibly()获取锁时，
 *      在线程调用interrupte()方法后，才会引发InterruptedException异常
 *  2.线程调用interrupt()之后，线程的中断标志会被置为true
 *  3.触发InterruptedException异常之后，线程的中断标志又会被清空，即置为false
 *  4.所以当线程调用interrupt（）方法 触发 InterruptedException异常，中断标志的变化
 *      是 false->true->false
 *
 */
public class Demo1 {
    private static ReentrantLock lock1 = new ReentrantLock();
    private static ReentrantLock lock2 = new ReentrantLock();

    public static class T extends Thread {
        int lock;

        public T(String name, int lock) {
            super(name);
            this.lock = lock;
        }

        @Override
        public void run() {
            try {
                if (this.lock == 1) {
                    lock1.lockInterruptibly();
                    TimeUnit.SECONDS.sleep(1);
                    lock2.lockInterruptibly();
                } else {
                    lock2.lockInterruptibly();
                    TimeUnit.SECONDS.sleep(1);
                    lock1.lockInterruptibly();
                }
            } catch (Exception e) {
                System.out.println("中断标志" + this.isInterrupted());
                System.out.println(e.getMessage());
                e.printStackTrace();
            } finally {
                if (lock1.isHeldByCurrentThread())
                    lock1.unlock();
                if (lock2.isHeldByCurrentThread())
                    lock2.unlock();
            }
        }

        public static void main(String[] args) throws Exception{
            T t1 = new T("t1",1);
            T t2 = new T("t2",2);
            t1.start();
            t2.start();
            TimeUnit.SECONDS.sleep(5);
            t1.interrupt();
        }
    }
}
